package com.useeinfo.oa.modules.base.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.func.lang.StringUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.dao.DictInfoDao;
import com.useeinfo.oa.modules.base.entity.DictInfo;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.security.entity.SystemAuthority;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther: xudong.sun
 * @Date: 2018/12/7 10:52
 * @Description:
 */
@Service
public class DictInfoBiz extends CrudBiz<DictInfoDao, DictInfo> {

    public JSONObject getDictSelect(Enterprise enterprise, String typeCode) {
        QueryParam queryParam = new QueryParam(-1, -1);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        queryParam.getSqlMap().put("typeCode", typeCode);
        queryParam.setSqlOrder("order by id");
        JSONObject result = findJSONList(queryParam);
        return result;
    }

    public DictInfo getDict(Enterprise enterprise, String typeCode) {
        QueryParam queryParam = new QueryParam(-1, -1);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        queryParam.getSqlMap().put("typeCode", typeCode);
        List<DictInfo> list = findList(queryParam);
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }


    private Sheet sheet;
    private Row row;


    public synchronized ResultDto importDict(Workbook wb, Enterprise enterprise) {
        if (wb == null) {
            return ResultUtil.error("Workbook对象为空！");
        }
        sheet = wb.getSheetAt(0);
        int rowNum = sheet.getLastRowNum();
        row = sheet.getRow(0);
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            DictInfo dictInfo = new DictInfo();
            dictInfo.setPropertyName(StringConverters.null2String(getCellFormatValue(row.getCell(0))));
            dictInfo.setPropertyCode(StringConverters.null2String(getCellFormatValue(row.getCell(1))));
            dictInfo.setTypeName(StringConverters.null2String(getCellFormatValue(row.getCell(2))));
            dictInfo.setTypeCode(StringConverters.null2String(getCellFormatValue(row.getCell(3))));
            dictInfo.setEnterprise(enterprise);
            addOrUpdate(dictInfo);
        }
        return ResultUtil.success();
    }

    public ResultDto checkData(Workbook wb, Enterprise enterprise) {
        if (wb == null) {
            return ResultUtil.error("Workbook对象为空！");
        }
        sheet = wb.getSheetAt(0);
        int rowNum = sheet.getLastRowNum();
        row = sheet.getRow(0);
        JSONArray result = new JSONArray();
        JSONObject jsonObject;
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            if (StringUtils.isBlank(StringConverters.null2String(getCellFormatValue(row.getCell(0))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据第" + (i + 1) + "行，属性名称数据存在问题，请确认后重新提交");
                result.add(jsonObject);
            }

            if (StringUtils.isBlank(StringConverters.null2String(getCellFormatValue(row.getCell(1))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据第" + (i + 1) + "行，属性编码数据存在问题，请确认后重新提交");
                result.add(jsonObject);
            }

            if (StringUtils.isBlank(StringConverters.null2String(getCellFormatValue(row.getCell(2))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据第" + (i + 1) + "行，类型名称数据存在问题，请确认后重新提交");
                result.add(jsonObject);
            }

            if (StringUtils.isBlank(StringConverters.null2String(getCellFormatValue(row.getCell(3))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据第" + (i + 1) + "行，类型编码数据存在问题，请确认后重新提交");
                result.add(jsonObject);
            }
        }
        if (result.size() > 0) {
            ResultDto resultDto = new ResultDto();
            resultDto.setStatus(1);
            resultDto.setData(result);
            resultDto.setMsg("导入失败");
            return resultDto;
        }
        return ResultUtil.success();
    }


    private Object getCellFormatValue(Cell cell) {
        Object cellvalue = "";
        if (cell != null) {
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:// 如果当前Cell的Type为NUMERIC
                case Cell.CELL_TYPE_FORMULA: {
                    // 判断当前的cell是否为Date
                    if (DateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        cellvalue = date;
                    } else {
                        DecimalFormat dfs = new DecimalFormat("0");
                        cellvalue = dfs.format(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                default:// 默认的Cell值
                    cellvalue = "";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;
    }


    //获取数据
    public List<SelectVO> getDictInfoMagic(String enterpriseId,String q,String id,String typeCode){
        //下面保证默认选择项加载正常
        String index = "";
        boolean status = false;//表示默认list中无此id的数据
        DictInfo dictInfo = dao.findModel(StringConverters.null2Long(id));
        if (org.apache.commons.lang.StringUtils.isBlank(q) && dictInfo != null) {
            index = id;
        }
        List<SelectVO> selectVOS = new ArrayList<>();
        QueryParam queryParam = new QueryParam(1, 20);
        if (enterpriseId != null) {
            queryParam.getSqlMap().put("enterpriseId", enterpriseId);
        }
        queryParam.getSqlMap().put("typeCode", typeCode);
        queryParam.getSqlMap().put("magicLike", q);
        queryParam.getSqlMap().put("magicId", id);
        List<DictInfo> dictInfoList = dao.findList(queryParam);
        if (CollectionUtils.isNotEmpty(dictInfoList)) {
            for (DictInfo dictInfo1 : dictInfoList) {
                if (org.apache.commons.lang.StringUtils.isNotBlank(index) && index.equals(dictInfo1.getId() + "")) {
                    status = true;
                }
                selectVOS.add(new SelectVO(dictInfo1.getPropertyName(), dictInfo1.getId() + ""));
            }
        }
        if (!status && dictInfo != null) {
            selectVOS.add(new SelectVO(dictInfo.getPropertyName(), dictInfo.getId() + ""));
        }
        return selectVOS;
    }
}
